using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using MSH = Microsoft.SPOT.Hardware;

namespace LBNHelpers
{
	public class I2CDevice : IDisposable
	{
		#region Public properties

		public ushort Address { get; internal set; }
		public int TimeOut { get; set; }

		#endregion

		#region Public interface

		public void ReadPort(byte port, ref byte[] result, int timeout = 100)
		{
			if (OwnerBus == null) throw new BusDestroyedException();
			OwnerBus.ReadPort(Address, port, ref result, timeout);
		}

		public byte[] ReadPort(byte port, byte sizetoread, int timeout = 100)
		{
			if (OwnerBus == null) throw new BusDestroyedException();
			return OwnerBus.ReadPort(Address, port, sizetoread, timeout);
		}

		public byte ReadPortByte(byte port, int timeout = 100)
		{
			if (OwnerBus == null) throw new BusDestroyedException();
			return OwnerBus.ReadPortByte(Address, port, timeout);
		}

		public int WritePort(byte port, byte data, int timeout = 100)
		{
			if (OwnerBus == null) throw new BusDestroyedException();
			return OwnerBus.WritePort(Address, port, data, timeout);
		}

		public int WritePort(byte port, byte[] data, int timeout = 100)
		{
			if (OwnerBus == null) throw new BusDestroyedException();
			return OwnerBus.WritePort(Address, port, data, timeout);
		}

		#endregion

		#region Internal data

		internal I2CBus OwnerBus;

		#endregion

		#region Internal constructor

		internal I2CDevice(I2CBus owner, ushort address, int timeout)
		{
			OwnerBus = owner;
			Address = address;
			TimeOut = timeout;
		}

		#endregion

		public void Dispose()
		{
			if (OwnerBus != null)
			{
				if (OwnerBus._DeviceList.Contains(this))
				{
					OwnerBus._DeviceList.Remove(this);
				}
			}
		}
	}
}
